package com.zx.platform.controller;


import com.zx.platform.service.OperatorInfoService;
import com.zx.platform.service.RolesService;
import com.zx.platform.service.domain.ManageSessionDomain;
import com.zx.platform.service.domain.OperatorInfoDomain;
import com.zx.platform.service.model.OperatorInfoModel;
import com.zx.platform.service.model.RolesModel;
import com.zx.platform.service.model.UserPasswordInfoModel;
import com.zx.platform.utils.DesUtil;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/manage/operatorInfo")
public class OperatorInfoController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(OperatorInfoController.class);

	@Autowired
	private OperatorInfoService operatorInfoService;
	
	@Autowired
	private RolesService rolesService;

	/**
	 * 进入列表页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/list")
	public String list(OperatorInfoDomain domain, Model model,
			HttpServletRequest request) {

		try {// 初始化信息
			Integer pageNum = domain.getPageNum();
			Integer pageSize = domain.getPageSize();
			Integer pageCount = domain.getPageCount();
			if (null == pageNum) {
				pageNum = 1;
			}
			if (null == pageSize) {
				pageSize = 10;
			}
//			只查询系统操作员
//			domain.setOperatorType("1");
			if(StringUtils.isEmpty(domain.getOperatorType())){
				domain.setOperatorType("1");
			}
			Map map = operatorInfoService.getPageByDomain(pageSize, pageNum, domain);
			List<OperatorInfoModel> operatorInfoModelList = (List<OperatorInfoModel>) map.get("list");
			int recordCount = Integer.valueOf(map.get("count").toString());
			// 页面信息
			if (pageSize * pageNum > recordCount + pageSize - 1) {
				pageNum = 1;
			}
			model.addAttribute("list", operatorInfoModelList);
			model.addAttribute("pageNum", pageNum);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageCount",
					PmpUtils.getPageCount(recordCount, pageSize));
			model.addAttribute("recordCount", recordCount);
			model.addAttribute("model", domain);
			return "/jsp/platform/operatorInfo/operatorInfoList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}
	/**
	 * 修改密码页面
	 * @param userPasswordInfoModel
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/preModifyPassword")
    public String preModifyPassword(UserPasswordInfoModel userPasswordInfoModel, Model model, HttpServletRequest request) {
    	try{
	        return "/jsp/platform/operatorInfo/preModifyPassword";
	    } catch (Exception e) {
	    	e.printStackTrace();
	        log.error("内部异常", e);
	        model.addAttribute("errorMsg", "出错了");
	        return "/jsp/platform/error";
	    }
    }
	/**
	  * 修改密码的ajax方法 
     * @return
     */
    @RequestMapping("/modifyPassword")
    public
    @ResponseBody
    Map modifyPassword(HttpServletRequest request) {
        Map map = new HashMap();
        try {
            String oldPassword = request.getParameter("oldPassword");
            String newPassword = request.getParameter("newPassword");
            ManageSessionDomain userinfo = (ManageSessionDomain) request.getSession().getAttribute("_LOGONUSER_");
            OperatorInfoModel operatorInfoModel = userinfo.getOperatorInfoModel();
            String loginPassword = operatorInfoModel.getLoginPassword();

            String state = "1";
            if(loginPassword.equals(DesUtil.encrypt(oldPassword, null))){
        		operatorInfoModel.setLoginPassword(DesUtil.encrypt(newPassword, null));
        		operatorInfoService.update(operatorInfoModel);
        		state = "a_1";//修改登录密码成功
        	}else{
        		state = "a_0";//原登录密码不正确
        	}
            map.put("state", state);
        } catch (Exception e) {
            map.put("state", 0);
            log.error("查询相关信息失败" + e.getMessage(), e);
        }
        return map;
    }
    /**  
     * 表单提交日期绑定  
     */  
    @InitBinder  
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    }
    /**
     * 弹出的新增修改页面
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public String edit(OperatorInfoModel operatorInfoModel, Model model, HttpServletRequest request) {
    	try{

            String operatorId = operatorInfoModel.getOperatorId();
    		if(!"add".equals(operatorId)&&StrUtils.isNotEmpty(operatorId)){
    			operatorInfoModel=operatorInfoService.getModelByKey(operatorId);
    			operatorInfoModel.setLoginPassword(DesUtil.decrypt(operatorInfoModel.getLoginPassword(), null));
    		}
	    	model.addAttribute("model", operatorInfoModel);
	        return "/jsp/platform/operatorInfo/operatorInfoEdit";
	    } catch (Exception e) {
	        log.error("内部异常", e);
	        model.addAttribute("errorMsg", "出错了");
	        return "/jsp/platform/error";
	    }
    }
    /**
     * @return
     */
    @RequestMapping("/update")
    public
    @ResponseBody
    OperatorInfoModel update(OperatorInfoModel model) {
        try {
        	model.setUpdateDate(new Date());
        	model.setLoginPassword(DesUtil.encrypt(model.getLoginPassword(), null));
        	operatorInfoService.update(model);
        	model.setSuccess(true);
        	model.setMsg("保存信息成功");
            log.debug("保存信息成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("保存信息失败");
            log.error("保存信息失败" + e.getMessage(), e);
        }
        return model;
    }

    /**
     * @return
     */
    @RequestMapping("/delete")
    public
    @ResponseBody
    OperatorInfoModel delete(OperatorInfoModel model) {
        try {
        	operatorInfoService.delete(model);
        	model.setSuccess(true);
        	model.setMsg("删除信息成功");
            log.debug("删除信息成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("删除信息失败");
            log.error("删除信息失败" + e.getMessage(), e);
        }
        return model;
    }

    /**
     * @return
     */
    @RequestMapping("/add")
    public
    @ResponseBody
    OperatorInfoModel add(OperatorInfoModel model) {
        try {
        	model.setCreateDate(new Date());
        	model.setUpdateDate(new Date());
        	model.setLoginPassword(DesUtil.encrypt(model.getLoginPassword(), null));
        	//操作员为系统人员
        	//操作员类型为代理人
        	//如果为空，默认设置为代理 edit by wenjw 2016.9.28
        	if(StringUtils.isEmpty(model.getOperatorType())){
        		model.setOperatorType("2");
        	}
        	operatorInfoService.add(model);
        	model.setSuccess(true);
        	model.setMsg("新增信息成功");
            log.debug("新增信息成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("新增信息失败");
            log.error("新增信息失败" + e.getMessage(), e);
        }
        return model;
    }
    /**
     * 设置角色
     * @param request
     * @return
     */
    @RequestMapping("/editOperatorRoles")
    public String editOperatorRoles(OperatorInfoModel operatorInfoModel, Model model, HttpServletRequest request) {
    	try{
            String operatorId = operatorInfoModel.getOperatorId();
            //查出当前操作人员的角色
            List<RolesModel> roleList = operatorInfoService.getRoleListByOperatorId(operatorId);
            
            //查出所有角色
            List allRoles = rolesService.getAllList();
            operatorInfoModel = operatorInfoService.getModelByKey(operatorId);
	    	model.addAttribute("model", operatorInfoModel);
	    	model.addAttribute("allRoles", allRoles);
	    	model.addAttribute("roleList", roleList);
	        return "/jsp/platform/operatorInfo/editOperatorRoles";
	    } catch (Exception e) {
	        log.error("内部异常", e);
	        model.addAttribute("errorMsg", "出错了");
	        return "/jsp/platform/error";
	    }
    }

    /*@RequestMapping("/setOperatorInfoRoles")
    public
    @ResponseBody
    OperatorInfoModel setOperatorInfoRoles(OperatorRolesModel model) {
    	OperatorInfoModel operatorInfoModel = new OperatorInfoModel();
    	try {
    		operatorInfoService.setOperatorRoles(model);
    		operatorInfoModel.setSuccess(true);
    		operatorInfoModel.setMsg("设置角色成功");
    		log.debug("设置角色成功");
    	} catch (Exception e) {
    		operatorInfoModel.setSuccess(false);
    		operatorInfoModel.setMsg("角色菜单设置失败");
    		log.error("角色菜单设置失败" + e.getMessage(), e);
    	}
    	operatorInfoModel.setOperatorId(model.getOperatorId());
    	return operatorInfoModel;
    }*/

    //设置用户角色
	@RequestMapping("/setOperatorInfoRoles")
	public
	@ResponseBody
	OperatorInfoModel setOperatorInfoRoles(OperatorInfoModel model) {
		OperatorInfoModel operatorInfoModel = new OperatorInfoModel();
		try {
			OperatorInfoModel operatorInfoModels = operatorInfoService.getModelByKey(model.getOperatorId());
			String roleId = model.getRoleIds();
			String[] roleIds = roleId.split(";");
			Integer role = Integer.parseInt(roleIds[0]);
			operatorInfoModels.setRoleId(role);
			operatorInfoService.update(operatorInfoModels);
			operatorInfoModel.setSuccess(true);
			operatorInfoModel.setMsg("设置角色成功");
			log.debug("设置角色成功");
		} catch (Exception e) {
			operatorInfoModel.setSuccess(false);
			operatorInfoModel.setMsg("角色菜单设置失败");
			log.error("角色菜单设置失败" + e.getMessage(), e);
		}
		operatorInfoModel.setOperatorId(model.getOperatorId());
		return operatorInfoModel;
	}
}
